package com.example.springsecuritydemo.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springsecuritydemo.mapper.UserMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @ClassName MyUserDetailsServiceImpl
 * @Description TODO
 * @Author Mister-Lu
 * @Date 2021/12/20
 **/
public class MyUserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<com.example.springsecuritydemo.pojo.User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        com.example.springsecuritydemo.pojo.User mysqlUser=userMapper.selectOne(queryWrapper);
        Collection<GrantedAuthority> autorities = new ArrayList<>();
        //查询用户对应的权限信息
        List<String> list = userMapper.selectRoles(username);
        if(list != null && list.size()>0){
            for (String role : list) {
                autorities.add(new SimpleGrantedAuthority(role));
            }
        }

        if(mysqlUser == null){return null;}
        User user = new User(mysqlUser.getUserName(), mysqlUser.getPassword(), autorities);
        return user;
    }

}
